package com.jeffse.light.stream.core.server;

import com.jeffse.light.stream.core.handler.StreamServerHander;
import com.jeffse.light.stream.core.handler.decoder.DataStreamDecode;
import com.jeffse.light.stream.core.handler.encoder.DataStreamEncode;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.oio.OioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class StreamServer {
    public void start(int port) throws Exception {
        EventLoopGroup group = new OioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(group)
                    .channel(OioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch){
                            ch.pipeline().addLast(new DataStreamEncode());
                            ch.pipeline().addLast(new DataStreamDecode());
                            ch.pipeline().addLast(new StreamServerHander());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            log.info("StreamServer is starting in port: " + port);
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}